<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>07-watch和 watchEffect</title>
    <style>
      * {
        cursor: pointer;
        user-select: none;
      }
    </style>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="root"></div>

    <script>
      //watch侦听器

      const app = Vue.createApp({
        setup() {
          const { reactive, watch, toRefs, watchEffect } = Vue;

          const nameObj = reactive({ name: "云牧", englishName: "黛玉" });

          //  具备一定惰性  lazy
          //  参数可以拿到当前和原始的值
          //  可以侦听多个数据的变化 用一个侦听器去完成
          //watch(
          //  [
          //    () => nameObj.name,
          //    () => nameObj.englishName
          //  ],
          //  ([curName, curEng], [preName, preEng]) => {
          //    console.log(curName, preName, "------", curEng, preEng);
          //  }
          //);

          const stop1 = watch(
            () => nameObj.englishName,
            (currentValue, preValue) => {
              console.log(currentValue, preValue);

              setTimeout(() => {
                stop1();
              }, 4000);
            },
            {
              immediate: true,
            }
          );

          //立即执行  没有惰性 immediate
          //不需要传递你要侦听的内容  自动会感知代码依赖  不需要传递很多参数 只需要一个回调函数
          //不能获取之前的值
          //const stop = watchEffect(() => {
          //  console.log(nameObj.name);
          //  //console.log(nameObj.englishName);

          //  setTimeout(() => {
          //    stop()
          //  },4000)
          //});

          const { name, englishName } = toRefs(nameObj);

          return { name, englishName };
        },

        template: `
                    <div>
                       Name:<input v-model="name">
                    </div>
                    <div>
                       Name is {{name}}
                    </div>
                    <div>
                       englishName:<input v-model="englishName">
                    </div>
                    <div>
                       englishName is {{englishName}}
                    </div>
                `,
      });

      const vm = app.mount("#root");
    </script>
  </body>
</html>
